package com.upcode.weighing.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtil {

    private static final Logger logger = LoggerFactory.getLogger(MapUtil.class);

    private static String key = "0d4f76129ff7e8065d674bd6fc42fc1b";

    /**
     * 根据经纬度获取行政区域编码
     * @param lng
     * @param lat
     * @return
     */
    public static Map<String,Object> getAddressComponent(String lng, String lat) {
        Map<String,Object> result = new HashMap<>();
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(lng).append(",").append(lat);
        String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());
        logger.debug(String.format("根据经纬度查询高德地图地址信息返回[%s]",res));
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = String.valueOf(jsonObject.get("status"));
        if(StringUtils.equals("0",status) || null == jsonObject.get("regeocode")){
            return null;
        }
        JSONObject regeocodeJson = JSONObject.parseObject(JSON.toJSONString(jsonObject.get("regeocode")));
        if(null == regeocodeJson.get("addressComponent")){
            return null;
        }
        JSONObject addressComponentJson = JSONObject.parseObject(JSON.toJSONString(regeocodeJson.get("addressComponent")));
        if(null == addressComponentJson.get("adcode") || StringUtils.isBlank(String.valueOf(addressComponentJson.get("adcode")))){
            return null;
        }
        result.put("province",addressComponentJson.get("province"));
        result.put("city",addressComponentJson.get("city"));
        result.put("district",addressComponentJson.get("district"));
        result.put("adcode",addressComponentJson.get("adcode"));
        logger.debug(String.format("根据经纬度查询到的行政区域信息为[%s]",result));
        return result;
    }

    /**
     * 2.根据两个定位点的经纬度算出两点间的距离
     * @param startLonLat 起始经纬度
     * @param endLonLat 结束经纬度（目标经纬度）
     * @return 两个定位点之间的距离
     */
    public static Long getDistance(String startLonLat, String endLonLat) {
        Long result = null;
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&origins=").append(startLonLat ).append("&destination=").append(endLonLat);
        String res = sendGet("http://restapi.amap.com/v3/distance", s.toString());
        logger.debug(String.format("根据经纬度查询高德地图距离返回[%s]",res));
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = String.valueOf(jsonObject.get("status"));
        if(StringUtils.equals("0",status) || null == jsonObject.get("results")){
            return result;
        }
        JSONArray ja = jsonObject.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        if(null == jobO.get("distance")){
            return result;
        }
        result = Long.parseLong(jobO.get("distance").toString());
        logger.debug(String.format("根据两点经纬度查询到的距离为[%s]米",result));
        return result;
    }

    /**
     * 根据详细地址获取经纬度信息
     * @param address
     * @return
     */
    public static Map<String,String> getGeocodeByAddress(String address) {
        Map<String,String> result = new HashMap<>();
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&output=json").append("&address=").append(address);
        String res = sendGet("https://restapi.amap.com/v3/geocode/geo", s.toString());
        logger.debug(String.format("根据详细地址查询省市区号以及经纬度信息，地址信息为[%s],高德API返回[%s]",address,res));
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = String.valueOf(jsonObject.get("status"));
        if(StringUtils.equals("0",status) || null == jsonObject.get("geocodes")){
            return null;
        }
        JSONArray geocodes = jsonObject.getJSONArray("geocodes");
        if(null == geocodes || geocodes.size() == 0){
            return result;
        }
        JSONObject geocode = JSONObject.parseObject(geocodes.getString(0));
        if(null == geocode.get("adcode") || null == geocode.get("location")){
            return result;
        }
        result.put("adcode",geocode.get("adcode").toString());
        result.put("location",geocode.get("location").toString());
        String formatted_address = geocode.get("formatted_address").toString();
        formatted_address = formatted_address.replace("|","");
        result.put("formatted_address",formatted_address);
        logger.debug(String.format("根据详细地址查询省市区号以及经纬度信息，高德API返回[%s]",JSON.toJSONString(result)));
        return result;
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try{
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        }catch (Exception e){
            logger.error(String.format("请求高德地图API异常,异常信息为[%s]",e.getMessage()),e);
        } // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error(String.format("请求高德地图API异常,异常信息为[%s]",ex.getMessage()),ex);
            }
        }
        return result;
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try{
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                logger.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }catch (Exception e){
            logger.error(String.format("请求高德地图API异常,异常信息为[%s]",e.getMessage()),e);
        }// 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                logger.error(String.format("请求高德地图API异常,异常信息为[%s]",e2.getMessage()),e2);
            }
        }
        return result;
    }
}
